// 考核指标管理 编辑
import type { FormInstance } from 'element-plus'
import type { OrserSetOption, formNameAndValueStateType } from '../typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElForm, ElFormItem, ElButton, ElInput, ElMessage } from 'element-plus'
import { handleTrim } from '~/utils/util'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'AssessManageOption',
  props: ['visible', 'title', 'record', 'original', 'allName', 'assessManageKey'],
  emits: ['cancel'],
  setup(props: OrserSetOption, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>() // 表单
    const formState = reactive<formNameAndValueStateType['form']>({})
    Object.assign(formState, props.record)

    // 提交前
    const updOrEditSubmit = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (valid) {
          formState.cfgTypeName = handleTrim(formState.cfgTypeName ?? '') // 去输入的前后空格
          if (
            // 验证
            props.original !== formState.cfgTypeName &&
            props.allName?.indexOf(formState.cfgTypeName!) !== -1
          ) {
            ElMessage({
              message: '此考核指标 已存在',
              type: 'warning'
            })
          } else {
            // 提交
            const realForm = JSON.parse(JSON.stringify(formState))
            if (realForm.cfgValue) {
              delete realForm.cfgValue
            }
            realForm.cfgValue = parseInt(formState.cfgValue!)
            realForm.cfgTypeCode = props.assessManageKey
            // 点"确定"后调接口保存编辑内容 并刷新
            const res = await store.dispatch('order/PostOrderSetUpdate', realForm)
            if (res?.code === 200) {
              handleCloseModal()
              if (!formEl) return
              formEl.resetFields()
              ElMessage({ message: '操作成功', type: 'success' })
            } else {
              ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
            }
          }
        } else {
          return false
        }
      })
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 考核时间
    const handleTimeOnInput = () => {
      if (parseInt(formState.cfgValue!) < 1) {
        formState.cfgValue = ''
      }
      formState.cfgValue = formState.cfgValue?.replace(/[^\d]/g, '')
    }

    return () => {
      const { title, visible } = props

      return (
        <ElDialog
          title={title}
          modelValue={visible!}
          append-to-body
          width="400px"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
        >
          <ElForm
            ref={ruleFormRef}
            model={formState}
            label-width="100px"
            class={styles['orderSet-assess']}
          >
            <ElFormItem
              label="指标名称"
              prop="cfgTypeName"
              rules={[{ required: true, message: '请输入指标名称', trigger: 'change' }]}
            >
              <ElInput
                class={styles['orderSet-input']}
                v-model={formState.cfgTypeName}
                placeholder="请输入指标名称"
                clearable
              />
            </ElFormItem>
            <ElFormItem
              label="考核时间"
              prop="cfgValue"
              rules={[
                { required: true, message: '请输入考核时间(大于等于1的正整数)', trigger: 'change' }
              ]}
            >
              <ElInput
                clearable
                class={styles['orderSet-input']}
                v-model={formState.cfgValue}
                onInput={handleTimeOnInput}
                placeholder="请输入大于等于1的正整数"
              >
                {{
                  suffix: () => <span class={styles['orderSet-hours']}>小时</span>
                }}
              </ElInput>
            </ElFormItem>
          </ElForm>
          <div class={styles['confirm-button']}>
            <ElButton class={styles['confirm-button-cancel']} plain onClick={handleCloseModal}>
              取 消
            </ElButton>
            <ElButton
              class={styles['confirm-button-submit']}
              type="primary"
              onClick={() => updOrEditSubmit(ruleFormRef.value)}
            >
              确 定
            </ElButton>
          </div>
        </ElDialog>
      )
    }
  }
})
